//
//  WeiboHelper.swift
//  ShareSina
//
//  Created by linhan on 15/7/9.
//  Copyright (c) 2015年 linhan. All rights reserved.
//

import Foundation

enum WeiboErrorCode:Int
{
    case Auth_Denied
    case Auth_Cancel
    case Fail
}

class WeiboSignInUser:NSObject
{
    var uid:String
    //昵称
    var screenName:String = ""
    
    //头像
    var avatarURL:String = ""
    
    var accessToken:String = ""
    
    var gender:String = ""
    
    var location:String = ""
    
    init(id:String)
    {
        uid = id
    }
}

protocol WeiboHelperDelegate:NSObjectProtocol
{
     func weiboSignInFail(code:WeiboErrorCode)
    
     func weiboSignInSuccess(uid:String, userInfo:WeiboSignInUser?)
    
}

private var _manager:WeiboHelper?
class WeiboHelper: NSObject,WeiboSDKDelegate,WBHttpRequestDelegate
{
    static var redirectURI:String = ""
    weak var delegate:WeiboHelperDelegate?
    
    var user:WeiboSignInUser?
    
    private var _accessToken:String = ""
    private var _uid:String = ""
    
    private struct RequestTag
    {
        static let UserInfo:String = "UserInfo"
        static let Publish:String = "Publish"
    }
    
    class func shared() -> WeiboHelper
    {
        _manager = _manager ?? WeiboHelper()
        return _manager!
    }
    
    class var weiboAppInstalled:Bool
    {
        return WeiboSDK.isWeiboAppInstalled()
    }
    
    class func registerApp(appKey:String)
    {
        WeiboSDK.registerApp(appKey)
    }
    
    //MARK ============================================================================================
    //==============================            Public Method           ===============================
    //=================================================================================================
    
    func auth()
    {
        let request:WBAuthorizeRequest = WBAuthorizeRequest()
        request.scope = "email"
        request.redirectURI = WeiboHelper.redirectURI
        WeiboSDK.send(request)
    }
    
    func publish(text:String, imageData:Data?)
    {
        if WeiboSDK.isWeiboAppInstalled()
        {
            let message:WBMessageObject = WBMessageObject()
            if let data = imageData
            {
                let image:WBImageObject = WBImageObject()
                image.imageData = data
                message.imageObject = image
            }
            message.text = text
            
            let request:WBSendMessageToWeiboRequest = WBSendMessageToWeiboRequest()
            request.message = message
            WeiboSDK.send(request)
        }
        else
        {
            var url:String = "https://api.weibo.com/2/statuses/update.json"
            var parameters:[String:Any] = [:]
            parameters["status"] = text
            if let data = imageData
            {
                parameters["pic"] = data
                url = "https://api.weibo.com/2/statuses/upload.json"
            }
            
//            let request:WBHttpRequest = WBHttpRequest()
//            request.url = url
//            request.httpMethod = "POST"
//            request.params = parameters
//            request.delegate = self
//            request.tag = RequestTag.Publish
            
            //WBHttpRequest.requestWithAccessToken(_accessToken, url:url, httpMethod:"POST", params:parameters, delegate:self, withTag:RequestTag.Publish)
            WBHttpRequest(accessToken: _accessToken, url: url, httpMethod: "POST", params: parameters, delegate: self, withTag: RequestTag.Publish)
        }
        
        
    }
    
    func handleOpenURL(_ url:URL) -> Bool
    {
        return WeiboSDK.handleOpen(url, delegate: self)
    }
    
    //MARK ============================================================================================
    //==============================            Private Method          ===============================
    //=================================================================================================
    
    //授权失败
    private func signInFail(_ code:WeiboErrorCode)
    {
        delegate?.weiboSignInFail(code: code)
    }
    
    //授权成功
    private func signInSuccess(uid:String, userInfo:WeiboSignInUser?)
    {
        delegate?.weiboSignInSuccess(uid: uid, userInfo: userInfo)
    }
    
    private func getUserInfo(_ accessToken:String, uid:String)
    {
        let URL:String = "https://api.weibo.com/2/users/show.json"
        
        let parameters:[String:Any] = ["uid":uid]
        
//        let request:WBHttpRequest = WBHttpRequest()
//        request.url = URL
//        request.httpMethod = "GET"
//        request.params = parameters
//        request.delegate = self
//        request.tag = RequestTag.UserInfo
        
        
        //WBHttpRequest.requestWithAccessToken(accessToken, url:URL, httpMethod:"GET", params:parameters, delegate:self, withTag:RequestTag.UserInfo)
        WBHttpRequest(accessToken: _accessToken, url: URL, httpMethod: "GET", params: parameters, delegate: self, withTag: RequestTag.UserInfo)
        
    }
    
    //MARK ============================================================================================
    //==============================            WeiboSDKDelegate        ===============================
    //=================================================================================================
    
    func didReceiveWeiboRequest(_ request:WBBaseRequest)
    {
        //trace("didReceiveWeiboRequest:\(request)")
    }
    
    func didReceiveWeiboResponse(_ response:WBBaseResponse)
    {
        if let authorizeResponse = response as? WBAuthorizeResponse
        {
            //var userInfo:[NSObject:AnyObject] = response.requestUserInfo
            let statusCode:Int = response.statusCode.rawValue
            /**
            requestUserInfo:{
            "access_token" = "2.00qKo9uBddjo4B7025f264831lMOFC";
            "expires_in" = 128932;
            "remind_in" = 128932;
            uid = 1750473704;
            }**/
            
            if statusCode == 0
            {
                _accessToken = authorizeResponse.accessToken
                _uid = authorizeResponse.userID
                let expirationDate = authorizeResponse.expirationDate
                
                if _uid != ""
                {
                    if _accessToken != ""
                    {
                        getUserInfo(_accessToken, uid:_uid)
                    }
                    else
                    {
                        signInSuccess(uid: _uid, userInfo:nil)
                    }
                }
                else
                {
                    signInFail(WeiboErrorCode.Fail)
                }
            }
            else if statusCode == -1
            {
                signInFail(WeiboErrorCode.Auth_Cancel)
            }
            else if statusCode == -3
            {
                signInFail(WeiboErrorCode.Auth_Denied)
            }
            else
            {
                signInFail(WeiboErrorCode.Fail)
            }
            
        }
    }
    
    //MARK ============================================================================================
    //==============================        WBHttpRequestDelegate       ===============================
    //=================================================================================================
    
    /**
    收到一个来自微博Http请求的网络返回
    
    @param data 请求返回结果
    */
    func request(_ request:WBHttpRequest, didFinishLoadingWithDataResult data:Data)
    {
        var json:JSON = JSON(data:data as Data, options:JSONSerialization.ReadingOptions.mutableContainers)
        if request.tag == RequestTag.UserInfo
        {
            //获取不到用户昵称、性别等信息，但是依然需要能登陆
            if let _ = json["error_code"].string
            {
                signInSuccess(uid: _uid, userInfo:nil)
            }
            else
            {
                //print("json:\(json)")
                user = WeiboSignInUser(id: _uid)
                user?.screenName = json["screen_name"].stringValue
                user?.avatarURL = json["avatar_large"].stringValue
                user?.gender = json["gender"].stringValue
                user?.accessToken = _accessToken
                user?.location = json["location"].stringValue
                signInSuccess(uid: _uid, userInfo:user)
            }
        }
    }
    
    /**
    收到一个来自微博Http请求失败的响应
    
    @param error 错误信息
    */
    func request(_ request:WBHttpRequest, didFailWithError error:Error?)
    {
        if request.tag == RequestTag.UserInfo
        {
            signInSuccess(uid: _uid, userInfo:nil)
        }
    }
    
    
    
}
